package oktx.feign.config;

import oktx.JtaTransaction;
import oktx.TccTransaction;
import oktx.feign.FeignContext;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * Created by huangdachao on 2018/5/30 15:17.
 */
public class FeignBeanWrapper implements InvocationHandler {
    private InvocationHandler handler;

    public FeignBeanWrapper(InvocationHandler handler) {
        this.handler = handler;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        JtaTransaction jta = method.getAnnotation(JtaTransaction.class);
        TccTransaction tcc = method.getAnnotation(TccTransaction.class);
        if (jta != null || tcc != null) {
            FeignContext.getContext().setMethod(method).setArguments(args);
        }

        try {
            return handler.invoke(proxy, method, args);
        } finally {
            FeignContext.removeContext();
        }
    }
}
